package com.rpc.com.rpc.util;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.register.client.model.RegisterInfo;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.net.Socket;

public class SocketClientUtil {



    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<T> clz){
        return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{clz}, (InvocationHandler) (proxy, method, args) -> {
            String apiName = clz.getName() + "#" + method.getName();
            RegisterInfo apiInfo = getApiInfo(apiName);
            Socket socket = new Socket(apiInfo.getHost(), apiInfo.getPort());
            socket.getOutputStream();
            IoUtil.writeUtf8(socket.getOutputStream(), false, apiName);
            socket.shutdownOutput();
            String result = IoUtil.read(socket.getInputStream(), CharsetUtil.UTF_8);
            socket.shutdownInput();

//            socket.getOutputStream().close();
//            socket.getInputStream().close();
//            socket.close();
            return result;
        });
    }

    private static RegisterInfo getApiInfo(String apiName) {
        String post = HttpUtil.post("http://127.0.0.1:10010/getApiInfo", apiName);
        return JSONUtil.toBean(post, RegisterInfo.class);
    }
}
